from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action

from file_manage.model_serializers import FileManageSerializer
from file_manage.models import FileManage
from file_manage.serializers import FileUploadSerializer, FileUploadResponseSerializer
from file_manage.service import FileManageService
from utils.addons.permissions_addon import IsSuperUser, DownloadSelfFilePermission, DownloadFileTagPermission
from utils.addons.responses import SuccessResponse
from utils.decorators.common import add_attr
from utils.mixins.common_mixins.filters import AllLookupsFilterBackend
from utils.mixins.common_mixins.permissions import OperandHolder, OR
from utils.mixins.common_mixins.requests import LogicalDeleteModelViewSet


class FileManageViewSet(LogicalDeleteModelViewSet):
    queryset = FileManage.objects.filter(is_deleted=False)
    serializer_class = FileManageSerializer
    filter_backends = (AllLookupsFilterBackend,)
    filterset_fields = '__all__'

    @action(
        methods=['GET'],
        detail=True,
        url_path='download',
        url_name='download',
        permission_classes=[OperandHolder(OR, IsSuperUser, DownloadSelfFilePermission, DownloadFileTagPermission), ],
    )
    def download(self, request, *args, **kwargs):
        _instance = self.get_object()
        ret = FileManageService.download_file(_instance)
        return ret

    @swagger_auto_schema(
        operation_summary='上传文件',
        operation_description='上传文件',
        request_body=FileUploadSerializer(),
        responses={
            200: FileUploadResponseSerializer(),
        },
    )
    @action(
        methods=['POST'],
        detail=False,
        url_path='upload',
        url_name='upload',
    )
    @add_attr(risk_level=1)
    def upload(self, request, *args, **kwargs):
        data = request.data
        user = request.user
        _serializer = FileUploadSerializer(data=data)
        _serializer.is_valid(raise_exception=True)
        ret = FileManageService.upload_file(data, user)
        ret = FileManageSerializer(ret).data
        return SuccessResponse(data=ret, msg='上传文件成功')
